package com.zjw.zy.coreui.view

import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.*
import android.widget.ImageView
import androidx.core.view.get
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.zjw.zy.R
import com.zjw.zy.base.BaseRecyclerAdapter
import com.zjw.zy.base.BaseViewGroup
import com.zjw.zy.base.BaseViewHolder
import com.zjw.zy.bean.ImageInfo
import com.zjw.zy.utils.AnimationUtils
import com.zjw.zy.utils.LogUtils
import com.zjw.zy.utils.PathUtils
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.sqrt

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/10/27 11:12
 */
class ImageViewContent : BaseViewGroup {

    companion object {
        private const val TAG = "ImageViewContent"
    }

    private var mDistance: Float = 0f
    private var mPX: Float = 0f
    private var mPY: Float = 0f

    private val mContent: ViewPager2 by lazy { findViewById(R.id.image_view_content_main) }

    private val mAdapter: ContentAdapter = ContentAdapter()

    private var mListener: Listener? = null

    private val scaleGestureDetector: ScaleGestureDetector =
        ScaleGestureDetector(context, object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
            override fun onScale(detector: ScaleGestureDetector?): Boolean {
                if (detector == null) {
                    return false
                }
                getSelectView()?.apply {
                    this.scaleX = detector.scaleFactor
                    this.scaleY = detector.scaleFactor
                    this.pivotX = detector.focusX
                    this.pivotY = detector.focusY
                }
                return true
            }

            override fun onScaleBegin(detector: ScaleGestureDetector?): Boolean {

                return true
            }

            override fun onScaleEnd(detector: ScaleGestureDetector?) {
            }
        })

    private val gestureDetector: GestureDetector =
        GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
            override fun onSingleTapUp(e: MotionEvent?): Boolean {
                mListener?.onSingleTapUp()
                return true
            }

            override fun onLongPress(e: MotionEvent?) {
                mListener?.onLongPress()
            }
        })


    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    override fun onLayoutId(): Int {
        return R.layout.image_view_content
    }

    override fun onBindListener() {

    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev == null) {
            return false
        }

        if (ev.pointerCount >= 2) {
            processPointerTouch(ev)
            return true
        }
        //scaleGestureDetector.onTouchEvent(ev)
        gestureDetector.onTouchEvent(ev)
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 双指手势相关
     * */
    private fun processPointerTouch(ev: MotionEvent) {
        val distance = sqrt(
            (ev.getX(0) - ev.getX(1)).pow(2.0f)
                    + (ev.getY(0) - ev.getY(1)).pow(2.0f)
        )

        if (ev.actionMasked == MotionEvent.ACTION_POINTER_DOWN) {
            mDistance = distance
            mPX = ev.getX(0)
            mPY = ev.getY(0)
            return
        }
        if (ev.actionMasked == MotionEvent.ACTION_POINTER_UP) {
            mDistance = 0f
            mPX = 0f
            mPY = 0f
            return
        }

        if (ev.action == MotionEvent.ACTION_MOVE) {
            val scale = min(3.3f, distance / mDistance)
            handleScale(scale, mPX, mPY)
        }
    }

    private fun handleScale(scale: Float, px: Float, py: Float) {
        getSelectView()?.apply {
            this.pivotX = px
            this.pivotY = py
            this.scaleX = scale
            this.scaleY = scale
        }
    }

    private fun getSelectView(): View? {
        return (mContent.getChildAt(0) as? RecyclerView)?.getChildAt(0)
    }

    override fun onBindValue() {
        mContent.adapter = mAdapter
    }

    fun bindData(data: List<ImageInfo>, position: Int = 0) {
        mAdapter.notifyData(data)
        setPosition(position)
    }

    fun bindListener(listener: Listener) {
        mListener = listener
    }

    fun setPosition(position: Int) {
        mContent.setCurrentItem(position, false)
    }

    //当前图片映射地址
    fun getCurrentImagePath(): ImageInfo {
        val position = mContent.currentItem
        return mAdapter.data[position]
    }

    override fun onFindView(rootView: View) {}

    fun notifyImageInsert(imageInfo: ImageInfo) {
        mAdapter.data.add(imageInfo)
        mAdapter.notifyItemInserted(mAdapter.data.size - 1)
    }


    /**
     * 内部适配器
     * */
    private class ContentAdapter() :
        BaseRecyclerAdapter<ImageInfo, ContentHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContentHolder {
            val item = ImageView(parent.context)
            item.layoutParams = WindowManager.LayoutParams()
            return ContentHolder(item)
        }
    }

    private class ContentHolder(item: View) : BaseViewHolder<ImageInfo>(item) {

        private var mBitmap: Bitmap? = null

        override fun onBindListener() {

        }

        override fun onBindData(data: ImageInfo?) {
            data?.let {
                mBitmap?.recycle()
                mBitmap = PathUtils.getBitmapFromPath(it.path)
                (itemView as ImageView).setImageBitmap(mBitmap)
            }
        }

    }

    interface Listener {
        fun onSingleTapUp() {}
        fun onLongPress() {}
    }
}